#include "StdAfx.h"
#include "ESMTP.h"

#include <algorithm>

namespace libdmail
{
	

	ESMTP::ESMTP(void):mStatus(WELCOME), bSucceedGetResponse(false), mMail(NULL)
	{
	}

	ESMTP::~ESMTP(void)
	{
	}

	int ESMTP::response(string responseText)
	{ 
		std::transform(responseText.begin(), responseText.end(), responseText.begin(), toupper);

		switch(this->mStatus)
		{
			case WELCOME:
				if ("220 ESMTP\r\n" == responseText)
				{
					this->mStatus = EHLO;
					bSucceedGetResponse = true;
				}
				break;

			case EHLO:
				if (string::npos != responseText.find("250 8BITMIME"))
				{
					this->mStatus = MAILFROM;
					bSucceedGetResponse = true;
				}
				break;

			case MAILFROM:
				if (string::npos != responseText.find("250"))
				{
					this->mStatus = RCPTTO;
					bSucceedGetResponse = true;
				}
				break;

			case RCPTTO:
				if (string::npos != responseText.find("250"))
				{
					this->mStatus = DATA;
					bSucceedGetResponse = true;
				}
				break;
			case DATA:
				if (string::npos != responseText.find("354 GO AHEAD"))
				{
					this->mStatus = DATATRANSFER;
					bSucceedGetResponse = true;
				}
				break;
			case DATATRANSFER:
				if (string::npos != responseText.find("250"))
				{
					this->mStatus = QUIT;
					bSucceedGetResponse = true;
				}
				break;
			default:
				break;
		}

		return bSucceedGetResponse;
	}

	string ESMTP::request()
	{
		string requestCommand = "NONE";

		if (bSucceedGetResponse)
		{
			switch(this->mStatus)
			{
			case EHLO:
				requestCommand = this->requestEHLO();
				bSucceedGetResponse = false;
				break;

			case AUTH:
				break;

			case MAILFROM:
				requestCommand = this->requestMAILFROM();
				bSucceedGetResponse = false;
				break;

			case RCPTTO:
				requestCommand = this->requestRCPTTO();
				bSucceedGetResponse = false;
				break;

			case DATA:
				requestCommand = this->requestDATA();
				bSucceedGetResponse = false;
				break;

			case DATATRANSFER:
				requestCommand = this->requestDATATransfer();
				
				bSucceedGetResponse = true;

				// Reach End of Mail File
				if ("\r\n.\r\n" == requestCommand)
				{
					requestCommand = this->requestDATAEND();
					bSucceedGetResponse = false;
				}

				break;
	 
			default:
				break;
			}
		}
		
		return requestCommand;
	}

	string ESMTP::requestEHLO()
	{
		return "EHLO\r\n";
	}

	string ESMTP::requestMAILFROM()
	{
		return "MAIL FROM:<ddd@gmail.com>\r\n";
	}

	string ESMTP::requestRCPTTO()
	{
		return "RCPT TO:<dengdongdong@300.cn>\r\n";
	}

	string ESMTP::requestDATA()
	{
		return "DATA\r\n";
	}

	string ESMTP::requestDATATransfer()
	{
		return this->mMail->readMail();
	}

	string ESMTP::requestDATAEND()
	{
		return "\r\n.\r\n";
	}

	string ESMTP::requestQUIT()
	{
		return "QUIT\r\n";
	}

	int ESMTP::setMail(Mail *mail)
	{
		this->mMail = mail;

		return 0;
	}
}